from django.shortcuts import render, HttpResponse, redirect
from web.forms.account import RegisterModelForm, SendSmsForm, SendSmsresetForm, LoginForm, ResetModelForm
from django.http import JsonResponse
from utils.imagecode import check_code
from io import BytesIO
from django.views.decorators.csrf import csrf_exempt
from web import models
from django.db.models import Q
import os
from django.contrib.sessions.models import Session


def register(request):
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'register.html', {'form': form})

    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        instance = form.save()
        return JsonResponse({'status': True, 'data': '/web/login/'})
    return JsonResponse({'status': False, 'error': form.errors})


def send_sms(request):
    if request.method == 'GET':
        if request.GET.get("flag") == '1':
            form = SendSmsresetForm(request, data=request.GET)
            if form.is_valid():
                return JsonResponse({'status': True})
            return JsonResponse({'status': False, 'error': form.errors})
        form = SendSmsForm(request, data=request.GET)
        if form.is_valid():
            return JsonResponse({'status': True})
        return JsonResponse({'status': False, 'error': form.errors})


def login(request):
    if request.method == 'GET':
        form = LoginForm(request)
        return render(request, "login.html", {'form': form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']

        user_object = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
            password=password).first()
        if user_object:
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60 * 60 * 24)

            return redirect("main.html")
        form.add_error('username', '用户名或密码错误')
    return render(request, 'login.html', {'form': form})


@csrf_exempt
def imagecode(request):
    img, code_string = check_code()
    request.session['image_code'] = code_string
    request.session.set_expiry(60)
    print(code_string)
    stream = BytesIO()
    img.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def loginplus(request):
    if request.method == 'GET':
        if request.session.get('user_id', None):
            return redirect("/web/wait")

        form = LoginForm(request)
        return render(request, "loginplus.html", {'form': form})
    form = LoginForm(request, data=request.POST)
    if form.is_valid():
        username = form.cleaned_data['username']
        password = form.cleaned_data['password']
        user_object = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
            password=password).first()

        if user_object:
            alluser = Session.objects.all()
            for oneuser in alluser:
                oneuser_status = oneuser.get_decoded()
                if oneuser_status.get('user_id', None) == user_object.id:
                    runuser_id = oneuser.session_key
                    Session.objects.get(pk=runuser_id).delete()
            request.session['user_id'] = user_object.id
            request.session['username'] = user_object.username
            request.session['email'] = user_object.email
            request.session.set_expiry(60 * 60 * 24)  # 用户保活状态持续一天
            return redirect("/web/wait")
        form.add_error('username', '用户名或密码错误')
    return render(request, 'loginplus.html', {'form': form})


def registerplus(request):
    if request.method == 'GET':
        form = RegisterModelForm()
        return render(request, 'registerplus.html', {'form': form})

    form = RegisterModelForm(data=request.POST)
    if form.is_valid():
        instance = form.save()
        return JsonResponse({'status': True, 'data': '/web/loginplus/'})
    return JsonResponse({'status': False, 'error': form.errors})


def logout(request):
    alluser = Session.objects.all()
    print(request.tracer.username)
    user_object = models.UserInfo.objects.filter(
        Q(email=request.tracer.email) | Q(mobile_phone=request.tracer.mobile_phone)).first()
    for oneuser in alluser:
        oneuser_status = oneuser.get_decoded()
        if oneuser_status.get('user_id', None) == user_object.id:
            runuser_id = oneuser.session_key
            Session.objects.get(pk=runuser_id).delete()
    request.session.flush()
    return redirect('/web/loginplus')


def resetplus(request):
    if request.method == 'GET':
        form = ResetModelForm()
        return render(request, 'resetplus.html', {'form': form})
    form = ResetModelForm(data=request.POST)
    if form.is_valid():
        mobile_phone = form.cleaned_data['mobile_phone']
        password = form.cleaned_data['password']
        instance = models.UserInfo.objects.filter(mobile_phone=mobile_phone).update(password=password)

        # instance = form.save()
        return JsonResponse({'status': True, 'data': '/web/loginplus/'})
    print('no')
    return JsonResponse({'status': False, 'error': form.errors})


def reset(request):
    if request.method == 'GET':
        form = ResetModelForm()
        return render(request, 'reset.html', {'form': form, 'a': request.tracer.mobile_phone})
    form = ResetModelForm(data=request.POST)
    if form.is_valid():
        mobile_phone = form.cleaned_data['mobile_phone']
        password = form.cleaned_data['password']
        instance = models.UserInfo.objects.filter(mobile_phone=mobile_phone).update(password=password)
        # instance = form.save()
        return JsonResponse({'status': True, 'data': '/web/resetright/'})
    print('no')
    return JsonResponse({'status': False, 'error': form.errors})


def wait(request):
    return render(request, 'wait.html')


def userexpired(request):
    return render(request, 'userexpired.html')

def resetright(request):
    return render(request, 'resetright.html')
